<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="会议题目" prop="meetingTitle">
        <el-input v-model="queryParams.meetingTitle" placeholder="请输入会议题目" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="计划开始时间" prop="plannedStartTime">
        <el-date-picker clearable v-model="queryParams.plannedStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm"
          placeholder="请选择计划开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="预约状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择预约状态" clearable>
          <el-option v-for="dict in day_meeting_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['day:application:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate"
          v-hasPermi="['day:application:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['day:application:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Download" @click="handleExport"
          v-hasPermi="['day:application:export']">导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applicationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请部门" align="center" prop="deptName" />
      <el-table-column label="会议题目" align="center" prop="meetingTitle" />
      <el-table-column label="会议室名称" align="center" prop="meetingRoomName" />
      <el-table-column label="计划开始时间" align="center" prop="plannedStartTime" width="140">
        <template #default="scope">
          <span>{{ parseTime(scope.row.plannedStartTime, '{y}-{m}-{d} {h}:{m}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="参会人数" align="center" prop="attendeeCount" />
      <el-table-column label="是否需要会标" align="center" prop="needBanner">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.needBanner" />
        </template>
      </el-table-column>
      <el-table-column label="会议类型" align="center" prop="meetingType">
        <template #default="scope">
          <dict-tag :options="day_meeting_type" :value="scope.row.meetingType" />
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applicant" />
      <el-table-column label="是否投屏" align="center" prop="needScreen">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.needScreen" />
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="day_meeting_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" size="small" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['day:application:edit']">修改</el-button>
          <el-button link type="primary" size="small" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['day:application:remove']">删除</el-button>
          <el-button link type="primary" size="small" icon="Check" @click="showReviewDialog(scope.row)"
            v-hasPermi="['day:application:status']">审核</el-button>
          <!-- 审核对话框 -->
          <!-- 审核对话框 -->
          <el-dialog title="审核申请" v-model="reviewDialogVisible" width="400px" append-to-body>
            <span>请确认是否通过审核？</span>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="handleReviewPass" type="success">审核通过</el-button>
                <el-button @click="handleReviewFail" type="danger">审核未通过</el-button>
                <el-button @click="handleReviewCancel">取消</el-button>
              </div>
            </template>
          </el-dialog>
        </template>

      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改会议室申请管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="applicationRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="会议题目" prop="meetingTitle">
          <el-input v-model="form.meetingTitle" placeholder="请输入会议题目" />
        </el-form-item>
        <el-form-item label="会议室名称" prop="meetingRoomId">
          <el-select v-model="form.meetingRoomId" placeholder="请选择会议室名称" clearable>
            <el-option v-for="dict in postOptions" :key="dict.id" :label="dict.meetingName" :value="dict.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划开始时间" prop="plannedStartTime">
          <el-date-picker clearable v-model="form.plannedStartTime" type="datetime" value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择计划开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="计划结束时间" prop="plannedEndTime">
          <el-date-picker clearable v-model="form.plannedEndTime" type="datetime" value-format="YYYY-MM-DD HH:mm"
            placeholder="请选择计划结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参会人数" prop="attendeeCount">
          <el-input v-model="form.attendeeCount" placeholder="请输入参会人数" />
        </el-form-item>
        <el-form-item label="开会主要内容">
          <el-input v-model="form.meetingContent" placeholder="请输入开会主要内容" />
        </el-form-item>
        <el-form-item label="会标" prop="needBanner">
          <el-select v-model="form.needBanner" placeholder="请选择是否需要会标">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="会标内容">
          <el-input v-model="form.bannerContent" placeholder="请输入会标内容" />
        </el-form-item>
        <el-form-item label="会议类型" prop="meetingType">
          <el-select v-model="form.meetingType" placeholder="请选择会议类型">
            <el-option v-for="dict in day_meeting_type" :key="dict.value" :label="dict.label"
              :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否投屏" prop="needScreen">
          <el-select v-model="form.needScreen" placeholder="请选择是否投屏">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="上传的会议材料" prop="meetingMaterials">
          <file-upload v-model="form.meetingMaterials" />
        </el-form-item>
        <el-form-item label="上传的会议议程" prop="meetingAgenda">
          <file-upload v-model="form.meetingAgenda" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup name="Application">
import { listApplication, getApplication, delApplication, addApplication, updateApplication, getMeetingRoomList } from "@/api/day/application";
import { ref, reactive, watch } from 'vue'
const { proxy } = getCurrentInstance();
const { day_meeting_status, day_meeting_type, sys_yes_no } = proxy.useDict('day_meeting_status', 'day_meeting_type', 'sys_yes_no');
const reviewDialogVisible = ref(false); // 控制审核弹窗的显示
const reviewStatus = ref(null); // 存储审核状态（1 为通过，2 为未通过）
const currentReviewId = ref(null); // 存储当前待审核的申请ID
const applicationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const postOptions = ref([]);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    meetingTitle: null,
    meetingRoomId: null,
    plannedStartTime: null,
    plannedEndTime: null,
    attendeeCount: null,
    meetingContent: null,
    needBanner: null,
    bannerContent: null,
    meetingType: null,
    applicant: null,
    needScreen: null,
    remarks: null,
    meetingMaterials: null,
    meetingAgenda: null,
    status: null
  },
  rules: {
    deptId: [
      { required: true, message: "申请部门ID不能为空", trigger: "change" }
    ],
    meetingTitle: [
      { required: true, message: "会议题目不能为空", trigger: "blur" }
    ],
    meetingRoomId: [
      { required: true, message: "会议室名称不能为空", trigger: "blur" }
    ],
    plannedStartTime: [
      { required: true, message: "计划开始时间不能为空", trigger: "blur" }
    ],
    plannedEndTime: [
      { required: true, message: "计划结束时间不能为空", trigger: "blur" }
    ],
    attendeeCount: [
      { required: true, message: "参会人数不能为空", trigger: "blur" }
    ],
    meetingContent: [
      { required: true, message: "开会主要内容不能为空", trigger: "blur" }
    ],
    /*needBanner: [
      { required: true, message: "是否需要会标不能为空", trigger: "change" }
    ],*/
    meetingType: [
      { required: true, message: "会议类型，枚举类型，可选值为“视频会议”或“座谈”不能为空", trigger: "change" }
    ],
    applicant: [
      { required: true, message: "申请人不能为空", trigger: "blur" }
    ],
    /*needScreen: [
      { required: true, message: "是否投屏不能为空", trigger: "change" }
    ],*/
  }
});

const { queryParams, form, rules } = toRefs(data);

// 显示审核对话框
function showReviewDialog(row) {
  currentReviewId.value = row.id; // 设置当前待审核的申请ID
  reviewDialogVisible.value = true; // 显示审核对话框
}

// 审核通过
function handleReviewPass() {
  submitReview(1);
}

// 审核未通过
function handleReviewFail() {
  submitReview(2);
}

// 取消审核
function handleReviewCancel() {
  reviewDialogVisible.value = false; // 关闭审核对话框
}

// 提交审核
function submitReview(status) {
  // 调用后端API更新审核状态
  updateApplication({ id: currentReviewId.value, status }).then(() => {
    proxy.$modal.msgSuccess("审核成功");
    reviewDialogVisible.value = false; // 关闭审核对话框
    getList(); // 刷新列表
  }).catch(() => {
    proxy.$modal.msgError("审核失败");
  });
}
/** 查询会议室申请管理列表 */
function getList() {
  loading.value = true;
  listApplication(queryParams.value).then(response => {
    applicationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  // 清空会议室列表
  postOptions.value = [];
  reset();
}
// 监听对话框状态变化
watchEffect(() => {
  if (open.value) {
    fetchMeetingRoomList();
  }
});
// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    meetingTitle: null,
    meetingRoomName: null,
    meetingRoomId: null,
    plannedStartTime: null,
    plannedEndTime: null,
    attendeeCount: null,
    meetingContent: null,
    needBanner: null,
    bannerContent: null,
    meetingType: null,
    applicant: null,
    needScreen: null,
    remarks: null,
    meetingMaterials: null,
    meetingAgenda: null,
    status: null
  };
  proxy.resetForm("applicationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  fetchMeetingRoomList()
  reset();
  open.value = true;
  title.value = "添加会议室申请管理";
  getList();

}

// 获取会议下拉列表的方法
function fetchMeetingRoomList() {
  getMeetingRoomList().then(response => {
    postOptions.value = response.rows; // 假设响应体中的rows字段包含了会议列表
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  fetchMeetingRoomList();
  reset();
  const _id = row.id || ids.value
  getApplication(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改会议室申请管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["applicationRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateApplication(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addApplication(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除会议室申请管理编号为"' + _ids + '"的数据项？').then(function () {
    return delApplication(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download('day/application/export', {
    ...queryParams.value
  }, `application_${new Date().getTime()}.xlsx`)
}

getList();
</script>
